/**
 * 
 */
package com.sx.core;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author FanGang
 * 
 */
public class MultiDataSource extends BasicDataSource implements DataSource, ApplicationContextAware {

	private static final Log log = LogFactory.getLog(MultiDataSource.class);
	private static final Map dataSources = new HashMap();// /数据源对象池

	private DataSource dataSource = null;// //默认数据源用于测试的数据源

	public Connection getConnection() throws SQLException {
		return getDataSource().getConnection();
	}

	public Connection getConnection(String arg0, String arg1)
			throws SQLException {
		return getDataSource().getConnection(arg0, arg1);
	}

	public PrintWriter getLogWriter() throws SQLException {
		return getDataSource().getLogWriter();
	}

	public int getLoginTimeout() throws SQLException {
		return getDataSource().getLoginTimeout();
	}

	public void setLogWriter(PrintWriter arg0) throws SQLException {
		getDataSource().setLogWriter(arg0);
	}

	public void setLoginTimeout(int arg0) throws SQLException {
		getDataSource().setLoginTimeout(arg0);
	}

	public DataSource getDataSource(String dataSourceName) {
		log.info("dataSourceName====>"+dataSourceName);
		if (dataSourceName == null || dataSourceName.equals("")) {
			return this.dataSource;
		}
		if (dataSources.get(dataSourceName) != null) {
			return (DataSource) dataSources.get(dataSourceName);
		} else {
			return createDataSource(SpObserver.getName(), SpObserver.getPass(),SpObserver.getUrl());
		}
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public DataSource getDataSource() {
		String sp = SpObserver.getName();
		return getDataSource(sp);
	}

	public DataSource createDataSource(String userName, String password,String url) {
		BasicDataSource s = new BasicDataSource();
		BasicDataSource ts = (BasicDataSource) dataSource;
		s.setUsername(userName);
		s.setPassword(password);
		s.setUrl(url);
		s.setDriverClassName(ts.getDriverClassName());
		dataSources.put(userName+url, s);
		return s;
	}

	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	public <T> T unwrap(Class<T> iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	public void setApplicationContext(ApplicationContext arg0)
			throws BeansException {
		// TODO Auto-generated method stub

	}
}
